import mx.controls.Label;

import schedule.*;
import schedule.ui.*;
import schedule.vk.*;

private var inputBox:GroupInputBox;
private var user:User;
private var currentGroup:int = 0;

private function init():void
{	
	AppData.viewerId = application.parameters.viewer_id;
	AppData.apiId = application.parameters.api_id;
	
	user = new User();
	user.addEventListener(User.LAST_GROUP_RETRIEVED, function(e:DataRetrievedEvent):void {
		var xml:String = e.retrievedData.toString();
		if (xml.length > 0) {
			var group:int = parseInt(xml, 10);
			if (ScheduleLoader.exists(group)) {
				currentGroup = group;
				updateMainPanel();
			}
		} else {
			showGroupPrompt();
		}
	});

	user.retrieveLastVisitedGroup();
}
			
private function showGroupPrompt():void
{
	if (inputBox == null) {
		inputBox = new GroupInputBox(this);

		inputBox.addEventListener(GroupInputBox.GROUP_SELECTED, function(e:GroupSelectedEvent):void {
			currentGroup = e.selectedGroup;
			updateMainPanel ();
			inputBox.hidePopup();
			user.setLastVisitedGroup(currentGroup);	
		});
	}
	
	inputBox.showPopup(currentGroup);
	currentGroup = 0;
}
			
private function updateMainPanel():void {
		mainPanel.title = "Расписание группы №" + currentGroup.toString();
		updateSchedule();
}

private function updateSchedule():void {
	scheduleItems.removeAllChildren();
	
	if (dateChooser.selectedDate == null)
		dateChooser.selectedDate = new Date ();
	
	var scheduleDay:Object = getScheduleDayData(dateChooser.selectedDate);
	if (scheduleDay == null)
		addSimpleLabel("Пока что расписание доступно с сентября по ноябрь.");
	else
		fillSchedule(scheduleDay);
}

private function getScheduleDayData(day:Date):Object {
	if (day.fullYear != 2009 || (day.month < 8 || day.month > 10)) { // sep to nov = 8 to 10
		return null;
	}
	
	var firstMonday:Date = new Date (2009, 7, 31);
	var diff:Number = (day.valueOf() - firstMonday.valueOf()) / (1000 * 60 * 60 * 24 * 7);
	var week:Number = Math.floor(diff) + 1;
	var weekday:Number = day.day;

	return {
		"weekday" : weekday,
		"week" : week
	};
}

private function fillSchedule(scheduleDay:Object):void 
{
	var week:int = scheduleDay.week;
	var weekday:int = scheduleDay.weekday;
	
	var even:Boolean = ((week % 2) == 0);
	var xml:XML = ScheduleLoader.getXML(currentGroup);
	var today:XMLList = xml.weekday.(@idx == weekday);
	var entries:XMLList = today.entry;

	var groupName:String = "Группа №" + currentGroup;

	if (entries.length() == 0) {
		addSimpleLabel(groupName + ", гуляем!", "hiliteyeah");
		return;
	}
	
	if (today.@moika == "true")
		addSimpleLabel(groupName + ". Здание на Мойке.", "hilite");
	else
		addSimpleLabel(groupName + ". Здание на Дыбенко.");
	
	for (var i:int = 0; i < entries.length (); i++) {
		var entry:XML = entries[i];
		var incl:Boolean = true;
		
		var practical:Boolean = (entry.@kind == "lab" || entry.@kind == "ex");
		var note:String = "";

		switch (entry.@condition.toString ()) {
			case "except12468":
			incl = (week == 3 || week == 5 || week == 7 || week > 8);
			note = "еж. кр. 1, 2, 4, 6, 8 нед.";
			break;
			
			case "even":
			incl = even;
			note = "ч/н";
			if (practical)
				incl = incl && (week >= 3);
			break;
			
			case "odd":
			incl = !even;
			note = "н/н";
			if (practical)
				incl = incl && (week >= 4);
			break;
			
			default:
			if (practical)
				incl = incl && (week >= 2);
			note = "еж.";
			break;
		}
		
		if (!incl)
			continue;
			
		var timing:String = entry.@starts + " - " + entry.@ends;
		var kind:String = "           "; // a bit ugly hack to make all titles go along

		if (practical) {
			if (entry.@kind == "ex")
				kind = "(упр)";
			else if (entry.@kind == "lab")
				kind = "(лаб)";
			else
				kind = "(???)";
		}	

		addLabel(timing, kind, entry.@name, entry.@room, note);
	}
}

private function addSimpleLabel(value:String, style:String = ""):void {
	var hbox:HBox = new HBox();
	
	var lbl:Label = new Label();
	lbl.text = value;
	
	if (style != "")
		lbl.styleName = style;

	hbox.addChild(lbl);
	
	scheduleItems.addChild(hbox);
}
			
private function addLabel(time:String, kind:String, subject:String, room:String, details:String):void {
	var hbox:HBox = new HBox();
	
	var timeLabel:Label = new Label();
	timeLabel.styleName = "time";
	timeLabel.text = time;
	
	var kindLabel:Label = new Label();
	kindLabel.styleName = "kind";
	kindLabel.text = kind;
	
	var subjectLabel:Label = new Label();
	subjectLabel.styleName = "subject";
	subjectLabel.text = subject;
	
	var roomLabel:Label = new Label();
	roomLabel.styleName = "room";
	roomLabel.text = room;
	
	var detailsLabel:Label = new Label();
	detailsLabel.styleName = "details";
	detailsLabel.text = details;
	
	hbox.addChild(timeLabel);
	hbox.addChild(kindLabel);
	hbox.addChild(subjectLabel);
	hbox.addChild(roomLabel);
	hbox.addChild(detailsLabel);
	
	scheduleItems.addChild(hbox);
}
